import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/cookie'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/oj/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
      meta: {
        transition: 'fade'
      }
    },
    {
      path: '/',
      redirect: '/oj/login'
    },
    {
      path: '/oj/layout',
      name: 'layout',
      component: () => import('@/views/Layout.vue'),
      meta: {
        transition: 'slide-left'
      },
      children: [
        {
          path: 'question',
          name: 'question',
          component: () => import('@/views/Question.vue'),
          meta: {
            transition: 'slide-fade',
            keepAlive: true
          }
        },
        {
          path: 'exam',
          name: 'exam',
          component: () => import('@/views/Exam.vue'),
          meta: {
            transition: 'slide-fade',
            keepAlive: true
          }
        },
        {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('@/views/updateExam.vue'),
          meta: {
            transition: 'scale'
          }
        },
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/Cuser.vue'),
          meta: {
            transition: 'slide-fade',
            keepAlive: true
          }
        }
      ]
    }
  ]
})

// 路由守卫优化
router.beforeEach((to, from, next) => {
  // 添加页面加载指示器
  if (typeof window !== 'undefined') {
    document.body.style.cursor = 'wait'
  }
  
  if (getToken()) {
    if (to.path === '/oj/login') {
      next({ path: '/oj/layout' })
    } else {
      next()
    }
  } else {
    if (to.path !== '/oj/login') {
      next({ path: '/oj/login' })
    } else {
      next()
    }
  }
})

router.afterEach(() => {
  // 移除页面加载指示器
  if (typeof window !== 'undefined') {
    document.body.style.cursor = 'default'
  }
})

export default router
